#pragma once
#include <iostream>
#include <functional>
#include <string>
const std::string oper = "+-*/%";
int myMath(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            std::cerr << "Error: div zero!" << std::endl;
            result = -1;
        }
        else
            result = x / y;
    }
    break;
    case '%':
    {
        if (y == 0)
        {
            std::cerr << "Error: mod zero!" << std::endl;
            result = -1;
        }
        else
            result = x % y;
    }
    break;
    default:
        break;
    }
    return result;
}
class CalTask
{
    using func_t = std::function<int(int, int, char)>;

public:
    CalTask() {}
    CalTask(int x, int y, char op, func_t func)
        : _x(x), _y(y), _op(op), _callBack(func)
    {
    }
    std::string operator()()// 消费者调用
    {
        int result = _callBack(_x, _y, _op);
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%d %c %d = %d", _x, _op, _y, result);
        return buffer;
    }
    std::string toString()// 生产者调用
    {
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%d %c %d = ?", _x, _op, _y);
        return buffer;
    }

private:
    int _x, _y;
    char _op;
    func_t _callBack; // 回调函数
};
class SaveTask
{
    using func_t = std::function<void(const std::string& )>;
public:
    SaveTask()
    {}
    SaveTask(const std::string& msg, func_t func)
        :_msg(msg)
        ,_func(func)
    {}
    void operator()()
    {
        _func(_msg);
    }
private:
    std::string _msg;
    func_t _func;
};
void Save(const std::string& msg)
{
    const char* target = "./log.txt";
    FILE* fp = fopen(target, "a+");
    if (fp == nullptr)
    {
        perror("fopen failed");
        return;
    }
    fputs(msg.c_str(), fp);
    fputs("\n", fp);
    fclose(fp);
}